<?php


namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Models\HouseSell;
use Illuminate\Http\Request;

class HouseSellController extends Controller
{
    public function index(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $offset = ($page == 1) ? 0 : ($page - 1) * $limit;


        //发布时间倒序
        $data = HouseSell::query()->with('community:community_id,community_name')->select('id', 'user_id', 'title', 'money', 'hot', 'image', 'house_type', 'community_id', 'room', 'hall', 'toilet', 'area', 'created_at')->orderByDesc('created_at')->offset($offset)->limit($limit)->get();
        $response['data'] = $data;
        $response['count'] = HouseSell::query()->count();
        $response['pages'] = ceil($response['count'] / $limit);
        return $this->success($response, '请求成功');
    }

    public function show($id)
    {
        $data = HouseSell::query()->with('community:community_id,community_address,city,community_name')->where('id', $id)->first()->toArray();
        if ($data) {
            $data['images'] = array_filter(explode(',', $data['images']), function ($item){
                return $item && true;
            });
        }

        return $this->success($data);
    }

    public function editHouseSellState(Request $request)
    {
        $id = $request->post('id');
        $hot = (HouseSell::query()->where('id', $id)->value('hot') == 1) ? 0 : 1;
        if ($id) {
            HouseSell::query()->where('id', $id)->update(['hot' => $hot]);
            return $this->success();
        }
    }
}
